package com.github.ghsea.scheduler.service;

import com.github.ghsea.scheduler.entity.AliveTaskStatistics;
import com.github.ghsea.scheduler.entity.TaskEntity;
import com.github.ghsea.scheduler.repository.TaskRepository;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author guhai
 * @since 2021/6/17 21:59
 */
@Service
public class TaskService {

    @Autowired
    private TaskRepository taskRepository;

    /**
     * TODO
     *
     * @return
     */
    public boolean isTaskAlive(String taskCode) {
        return Integer.valueOf(1).equals(taskRepository.isTaskAlive(taskCode));
    }

    public TaskEntity queryAliveTaskCode(String taskCode) {
        return taskRepository.queryAliveTaskCode(taskCode);
    }

    public void stopTask(String taskCode, Date stopTime) {
        taskRepository.stopTask(taskCode, stopTime);
    }

    public void insertTask(TaskEntity task) {
        taskRepository.insert(task);
    }

    /**
     * 根据taskId和version更新task所归属的server
     *
     * @param tasks
     */
    public void batchUpdateServerByTaskId(List<TaskEntity> tasks) {
        taskRepository.batchUpdateServerByTaskId(tasks);
    }


    /**
     * 分页查询某一个server所管理的并且还存活的task
     *
     * @param serverId
     * @param startId
     * @param limit
     * @return
     */
    public List<TaskEntity> fetchAliveTasks(String serverId, long startId, int limit) {
        return taskRepository.findAliveTasks(serverId, startId, limit);
    }

    /**
     * 根据serverId统计存活的task
     *
     * @param serverId
     * @return
     */
    public AliveTaskStatistics aliveTaskStatistics(String serverId) {
        return taskRepository.aliveTaskStatistics(serverId);
    }
}
